package logger

import (
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
	"os"
)

var logger *zap.SugaredLogger

//func LogInit() {
//LogInitWithConfig(NewLogConfig())
//}

func LogInit(cfg *LogConfig) {
	// 配置 lumberjack
	hook := &lumberjack.Logger{
		Filename:   cfg.Filename,
		MaxSize:    cfg.MaxSize,
		MaxBackups: cfg.MaxBackups,
		MaxAge:     cfg.MaxAge,
		Compress:   cfg.Compress,
	}

	loggerConFig(hook)
}

func loggerConFig(hook *lumberjack.Logger) {
	// 配置 Zap 的 EncoderConfig - JSON 格式
	encoderConfig := zapcore.EncoderConfig{
		TimeKey:        "time",
		LevelKey:       "level",
		NameKey:        "logger",
		CallerKey:      "caller",
		MessageKey:     "msg",
		StacktraceKey:  "stacktrace",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.LowercaseLevelEncoder,
		EncodeTime:     zapcore.ISO8601TimeEncoder,
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   zapcore.ShortCallerEncoder,
	}
	// 设置日志级别
	level := zap.InfoLevel

	// 同时输出到文件和控制台
	consoleEncoder := zapcore.NewConsoleEncoder(encoderConfig)
	fileEncoder := zapcore.NewJSONEncoder(encoderConfig)
	core := zapcore.NewTee(
		zapcore.NewCore(fileEncoder, zapcore.AddSync(hook), level),
		zapcore.NewCore(consoleEncoder, zapcore.AddSync(os.Stdout), level),
	)

	logger = zap.New(core, zap.AddCaller(), zap.AddCallerSkip(2)).Sugar()
	//输出一条日志
	logger.Info("logger init success")
}

// Debug 输出Debug级别日志
func Debug(args ...any) {
	logger.Debugln(args...)
}

// Info 输出Info级别日志
func Info(args ...any) {
	logger.Infoln(args...)
}

// Warn 输出Warn级别日志
func Warn(args ...any) {
	logger.Warnln(args...)
}

// Error 输出Error级别日志
func Error(args ...any) {
	logger.Errorln(args...)
}

// Fatal 输出Fatal级别日志
func Fatal(args ...any) {
	logger.Fatalln(args...)
}
